<script lang="ts">
import {Vue, Component, Prop, Inject, Watch, Emit} from 'vue-property-decorator';
import {AuditProps, AuditType} from "./types";
import {BrandDetail, CommodityReviewItem, CommonResult, TagEntity, CommodityLicenseDetail, PartnerLicenseDetail} from "../../plugins/dto";
import {AuditRequestFields, BusinessType, CommodityAuditFields, CommodityAuditInfo} from "../../type";
import CommodityClassify from "../Base/CommodityClassify/CommodityClassify.vue";
import {ClassifyProperties, OptionType} from "../Base/CommodityClassify/type";
import masterModal from "../../../../api/module/masterModal";
import {Tag} from "element-ui";
import EventBus from "../../eventBus/event";
@Component({
  model:{
    prop:"value",
    event: "update"
  },
    components: {CommodityClassify}
})

export default class AuditInfo extends Vue implements AuditProps{
  @Prop({default: ""})auditType!: AuditType;
  @Prop({type: Function})getField!: Function;
  private manageOptions:OptionType[] = []
  private physicalOptions:OptionType[] = []
  @Inject("businessType")
  providedBusinessType!: BusinessType;
  options=[
    {
      value: "口腔设备",
      label: "口腔设备",
      children: [
        {
          label: "影像设备",
          value: "影像设备"
        }
      ]
    }
  ]
  approve: number = 1
  tagResult: string[] = []
  mdResult:number=1
  commodityTags:TagEntity[]=[]
  matchResult: string[] = [];
  auditContent: string = ""
  code:string = "" // 品牌缩写
  auditInfo:CommodityAuditInfo = {
    approve: 1,
    commodityCategory: {} as ClassifyProperties,
    managementCategory: "",
    physicalForm: "",
    tags: [],
    remark:"",
    code: ""
  }
  remark:string=""
  managementCategory:string = "";
  @Inject("CommodityDetail")
  providedCommodityDetail!: CommodityReviewItem

  @Inject("BrandDetail")
  providedBrandDetail!:BrandDetail
  
  @Inject("ApplyInfo")
  provideApplyInfo!: any

  @Inject('modeType') injectedModeType!: {mode: string};

  @Inject("CommodityLicenseDetail")
  providedCommodityLicenseDetail!:CommodityLicenseDetail

  @Inject("PartnerLicenseDetail")
  providedPartnerLicenseDetail!:PartnerLicenseDetail
  

  @Watch("providedCommodityDetail", {immediate: true, deep: true})
  commodityDetailChanged(newValue:CommodityReviewItem){
    this.auditInfo.managementCategory = newValue.managementCategory;
    this.auditInfo.physicalForm = newValue.physicalForm
    // const classMap = ['classFirst', 'classSecond', 'classThird', 'classFourth'];
    // classMap.forEach(classItem => {
      
    // })
    if (newValue.classFirst) this.auditInfo.commodityCategory.classFirst = newValue.classFirst;
    if (newValue.classSecond) this.auditInfo.commodityCategory.classSecond = newValue.classSecond;
    if (newValue.classThird) this.auditInfo.commodityCategory.classThird = newValue.classThird;
    if (newValue.classFourth) this.auditInfo.commodityCategory.classFourth = newValue.classFourth
    
  }

  @Watch("providedPartnerLicenseDetail", {immediate: true, deep: true})
  partnerLicenseDetailChanged(newValue:CommodityLicenseDetail){
    if (this.providedBusinessType.businessType === 'partnerLicense') {
      this.auditInfo.approve = newValue.status == -1 ? 0 : 1;
      this.auditInfo.remark = newValue.remark;
      this.remark = newValue.remark;
    }
    
  }

  @Watch("providedBrandDetail", {immediate: true, deep: true})
  providedBrandChanged(newValue:CommodityLicenseDetail){
    // if (this.providedBusinessType.businessType === 'brand') {
    //   this.auditInfo.approve = newValue.status == -1 ? 0 : 1;
    //   this.auditInfo.remark = newValue.remark;
    //   this.remark = newValue.remark;
    // }
    
  }
  

  @Watch("providedCommodityLicenseDetail", {immediate: true, deep: true})
  commodityLicenseDetailChanged(newValue:CommodityLicenseDetail){
    if (this.providedBusinessType.businessType === 'commodityLicense') {
      this.auditInfo.approve = newValue.status == -1 ? 0 : 1;
      this.auditInfo.remark = newValue.remark;
      this.remark = newValue.remark;
    }
    
  }

  @Watch("provideApplyInfo", {immediate: true, deep: true})
  applyInfoChanged(newValue:any){
    if (this.providedBusinessType.businessType === 'commodity') {
      this.auditInfo.approve = newValue.status == -1 ? 0 : 1;
      this.auditInfo.remark = newValue.remark;
      this.remark = newValue.remark;
    } else if (this.providedBusinessType.businessType === 'brand') {
      this.auditInfo.approve = newValue.status == -1 ? 0 : 1;
      this.auditInfo.remark = newValue.remark;
      this.remark = newValue.remark;
      this.auditInfo.code = newValue.code;
    }
  }
  @Emit("update")
  handleUpdate(value:AuditRequestFields){
    return value
  }
  async mounted(){
    const res:CommonResult<TagEntity[]> = await masterModal.getTagList({bizTable: this.providedBusinessType.businessType === 'commodity' ? "ap_commodity" : this.providedBusinessType.businessType === 'brand' ? 'ap_brand' : this.providedBusinessType.businessType === 'commodityLicense' ? 'ap_commodity_license' :  this.providedBusinessType.businessType === 'partnerLicense' ? 'ap_partner_license':'ap_commodity'});
    if(res.code == 200 && res.data){
      this.commodityTags = res!.data
    }
    const paramRes = await masterModal.getParamsData({strList: ["management_category", "physical_form"]})
    if (paramRes.data) {
      const manageOptions: OptionType[] = paramRes.data.filter(item => item.paramType === 'management_category').map(j => ({
        label: j.name,
        value: j.code
      }))
      const physicalOptions: OptionType[] = paramRes.data.filter(item => item.paramType === 'physical_form').map(j => ({
        label: j.name,
        value: j.code
      }))
      this.manageOptions = manageOptions
      this.physicalOptions = physicalOptions
    }
  }
  @Watch("auditInfo", {immediate: true, deep: true})
  handleAuditInfo(){
    // 转换数据
    let data:AuditRequestFields = <AuditRequestFields>{}
    for(let key in this.auditInfo){
      if(key==='commodityCategory'){
          data.classFirst = this.auditInfo.commodityCategory.classFirst
          data.classSecond = this.auditInfo.commodityCategory.classSecond
          data.classThird = this.auditInfo.commodityCategory.classThird
          data.classFourth = this.auditInfo.commodityCategory.classFourth
      }else if(key==='approve'){
        data["approve"] = this.auditInfo["approve"] === 1 ? true: false
      }else{
        //@ts-ignore
        data[key as any] = this.auditInfo[key as keyof typeof this.auditInfo] as any
      }
    }
    if(this.auditInfo.approve==0 && this.auditInfo.tags.length){
      
      this.auditInfo.remark = `${this.providedBusinessType.businessType === 'commodity' ? '商品' : this.providedBusinessType.businessType === "brand" ? "品牌" : "证照"}存在【${this.auditInfo.tags.join("、")}】请修正后重新申请;${this.remark}`
    }
    this.handleUpdate(data)
  }

  @Watch("remark", {immediate: true, deep: true})
  handleRemark(){
    if (this.auditInfo.tags.length) {
      this.auditInfo.remark = `${this.providedBusinessType.businessType === 'commodity' ? '商品' : this.providedBusinessType.businessType === "brand" ? "品牌" : "证照"}存在【${this.auditInfo.tags.join("、")}】请修正后重新申请;${this.remark}`
    } else {
      this.auditInfo.remark = this.remark
    }
  }
  @Watch("auditInfo.approve", {immediate: true, deep: true})
  handleResultChange(value:number, oldValue:number){
      if(this.auditInfo.remark){
        this.auditInfo.remark = ""
        this.auditInfo.tags = []
      }
  }

  auditSubmit(){
    EventBus.$emit("submitAudit");
  }
  validate(){
    return new Promise((resolve, reject) => {
      if([ "partnerLicense","commodityLicense","foreignLicense","domesticRecord","foreignRecord"].includes(this.providedBusinessType.businessType)){
        resolve(true)
      }else{
        if(this.auditInfo.approve == 1 && this.auditType == 'add'){
          //@ts-ignore
          this.$refs.form.validate((res:boolean)=>{
            if(res){
              resolve(true)
            }else{
              reject()
            }
          })
        }else if(this.auditInfo.approve == 0){
          //@ts-ignore
          this.$refs.formRefuse.validate((res:boolean)=>{
            if(res){
              resolve(true)
            }else{
              reject()
            }
          })
        } else if(this.auditInfo.approve == 1 && this.auditType == 'edit'){
          resolve(true)
        }
      }
    })
  }

  cancel(){
    EventBus.$emit("closeModal");
  }
  customValidator(rule:any, value:any, callback:Function){
    if(this.auditInfo.commodityCategory){
      if(Object.keys(this.auditInfo.commodityCategory).length>0){
        callback()
      }else{
        callback(new Error("请选择商品分类"))
      }
    }
  }
  validateBrand(rule:any, value:any, callback:Function){
    if(!this.auditInfo.code){
      callback(new Error("请生成品牌缩写"))
    }else if(this.auditInfo.code && !/^[a-zA-Z0-9]{3}$/.test(this.auditInfo.code)){
      callback(new Error("缩写需为三位字母/数字"))
    }else{
      callback()
    }
  }
  validateTags(rule:any, value:any, callback:Function){
    if(this.auditInfo.tags.length > 0){
        callback()
    }else {
      callback(new Error("请选择数据标签"))
    }
  }
  generateCode(){
    const {cnName, enName} = this.getField()
      masterModal.generateCode({id:this.providedBrandDetail.id, cnName, enName}).then((res:any)=>{
        if(res.code === 200){
          this.auditInfo.code = res.data
        }
      })
  }
  handleTagChange(values: any){
    // if(this.auditInfo.approve == 0){
    //   if(values.length){
    //     this.auditInfo.remark = `${this.providedBusinessType.businessType === 'commodity' ? '商品' : this.providedBusinessType.businessType === "brand" ? "品牌" : "证照"}存在【${values.join("、")}】请修正后重新申请`
    //   }else{
    //     this.auditInfo.remark = ""
    //   }
    // }
  }
}
</script>

<template>
  <div class="auditInfo">
    <div v-if="auditType!='match'" style="height: calc(100% - 50px)">
      <div class="cc-apply-audit-item display-noTop">
        <div class="cc-apply-audit-title">审批结果：</div>
        <el-radio-group v-model="auditInfo.approve" :disabled="injectedModeType.mode == 'preview'">
          <el-radio :label="1">审批通过</el-radio>
          <el-radio :label="0" class="reject">审批拒绝</el-radio>
        </el-radio-group>
      </div>
      <template v-if="auditInfo.approve===1">
        <template v-if="providedBusinessType.businessType === 'commodity' && auditType === 'add'">
          <el-form :inline="true" label-width="90px" :model="auditInfo" ref="form">
            <div class="cc-apply-audit-item display-noTop">
              <el-form-item label="商品分类：" :rules="[{validator: customValidator}]" prop="commodityCategory">
                <CommodityClassify v-model="auditInfo.commodityCategory"></CommodityClassify>
              </el-form-item>
            </div>
            <div class="cc-apply-audit-item display-noTop" v-if="providedCommodityDetail.commodityType !== 9">
              <el-form-item label="管理类别：" :rules="[{required: true, message: '请选择管理类别', trigger: 'blur'}]" prop="managementCategory">
                <el-select v-model="auditInfo.managementCategory" :disabled="injectedModeType.mode == 'preview'">
                  <el-option v-for="(item, index) in manageOptions" :label="item.label" :value="item.value" :key="index"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="cc-apply-audit-item display-noTop">
              <el-form-item label="物理形态：" :rules="[{required: true, message: '请选择物理形态', trigger: 'blur'}]" prop="physicalForm">
                <el-select v-model="auditInfo.physicalForm" :disabled="injectedModeType.mode == 'preview'">
                  <el-option v-for="(item, index) in physicalOptions" :label="item.label" :value="item.value" :key="index"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form>

        </template>
        <template v-if="providedBusinessType.businessType === 'brand' && auditType==='add'">
          <el-form :inline="true" label-width="90px" :model="auditInfo" ref="form">

            <div class="cc-apply-audit-item display-noTop">
              <el-form-item label="品牌缩写：" :rules="[{validator: validateBrand, trigger: 'blur'}]" prop="code">
                <div class="cc-apply-audit-content" style="position: relative">
                  <el-input  v-model.trim="auditInfo.code" :disabled="injectedModeType.mode == 'preview'"></el-input>
                  <i class="el-icon-refresh" style="cursor:pointer;position:absolute;right:12px; top: 12px" v-if="injectedModeType.mode != 'preview'" @click="generateCode"></i>
                </div>
              </el-form-item>
            </div>
          </el-form>
        </template>
      </template>
      <template v-if="auditInfo.approve===0">
        <div class="cc-apply-audit-item">
<!--          <div class="cc-apply-audit-title">数据标签：</div>-->
<!--          <div class="cc-apply-audit-content">-->
<!--            <el-checkbox-group v-model="auditInfo.tags" :disabled="injectedModeType.mode == 'preview'">-->
<!--              <el-checkbox v-for="(item, index) in commodityTags" :key="index" :value="item.code" :label="item.name"></el-checkbox>-->
<!--            </el-checkbox-group>-->
<!--          </div>-->
          <el-form label-width="90px" ref="formRefuse" :model="auditInfo" v-if="injectedModeType.mode != 'preview'">
            <el-form-item label="数据标签:" :rules="[{validator: validateTags}]" prop="tags">
              <div class="cc-apply-audit-content" >
                <el-checkbox-group v-model="auditInfo.tags" :disabled="injectedModeType.mode == 'preview'" @change="handleTagChange">
                  <el-checkbox v-for="(item, index) in commodityTags" :key="index" :value="item.code" :label="item.name"></el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <div class="cc-apply-audit-item">
        <div class="cc-apply-audit-title">审批意见：</div>
        <div class="cc-apply-audit-content">
          <el-input type="textarea" max="10" placeholder="请输入审批意见" v-model="remark" rows="8" :disabled="injectedModeType.mode == 'preview'">
          </el-input>
        </div>

      </div>
    </div>
    <div v-else style="height: calc(100% - 50px)">
      <div class="cc-apply-audit-item cc-apply-audit-title">
        处理结果
      </div>
      <div class="cc-apply-audit-item">
        <div class="cc-apply-audit-title">处理结果：</div>
        <div class="cc-apply-audit-content">
          <el-radio-group v-model="mdResult" :max="1" :disabled="injectedModeType.mode == 'preview'">
            <el-radio :label="1">新增并赋码</el-radio>
            <el-radio :label="2">更新并赋码</el-radio>
            <el-radio :label="3">赋码</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template v-if="mdResult===2">
        <div class="cc-apply-audit-item">
          <div class="cc-apply-audit-title">更新栏位：</div>
          <div class="cc-apply-audit-content">
            <template v-if="providedBusinessType.businessType==='commodity'">
              <el-checkbox-group v-model="matchResult" :disabled="injectedModeType.mode == 'preview'">
                <el-checkbox label="cnName">商品名称</el-checkbox>
                <el-checkbox label="specification">规格型号</el-checkbox>
                <el-checkbox label="articleNo">货号</el-checkbox>
                <el-checkbox label="minSaleUnit">基本单位</el-checkbox>
                <el-checkbox label="packageParam">包装参数</el-checkbox>
              </el-checkbox-group>
            </template>
            <template v-if="providedBusinessType.businessType==='brand'">
              <el-checkbox-group v-model="matchResult" :disabled="injectedModeType.mode == 'preview'">
                <el-checkbox label="cnName">品牌名称</el-checkbox>
                <el-checkbox label="enName">英文名称</el-checkbox>
                <el-checkbox label="companyName">品牌所属公司</el-checkbox>
              </el-checkbox-group>
            </template>
            <template v-if="providedBusinessType.businessType==='commodityLicense'">
              <el-checkbox-group v-model="matchResult" :disabled="injectedModeType.mode == 'preview'">
                <el-checkbox label="licenseCode">证照编号</el-checkbox>
                <el-checkbox label="productName">产品名称</el-checkbox>
                <el-checkbox label="specification">规格型号</el-checkbox>
                <el-checkbox label="approvalDepartment">审批部门</el-checkbox>
              </el-checkbox-group>
            </template>
            <template v-if="providedBusinessType.businessType==='partnerLicense'">
              <el-checkbox-group v-model="matchResult" :disabled="injectedModeType.mode == 'preview'">
                <el-checkbox label="licenseCode">证照编号</el-checkbox>
                <el-checkbox label="productName">产品名称</el-checkbox>
                <el-checkbox label="specification">规格型号</el-checkbox>
                <el-checkbox label="approvalDepartment">审批部门</el-checkbox>
              </el-checkbox-group>
            </template>
          </div>
        </div>
      </template>
      <div class="cc-apply-audit-item">
        <div class="cc-apply-audit-title">审批意见：</div>
        <div class="cc-apply-audit-content">
          <el-input type="textarea" max="10" placeholder="请输入审批意见" v-model="auditContent" rows="8" :disabled="injectedModeType.mode == 'preview'">

          </el-input>
        </div>

      </div>
    </div>
    <template v-if="auditType==='match' && injectedModeType.mode != 'preview'">
        <div style="height: 50px;border-top: 1px solid #f0f0f0;padding-top: 5px; display: flex; align-items: center;justify-content: right" class="cc-check-content__buttons">
          <el-button type="default" @click="cancel" :disabled="injectedModeType.mode == 'preview'">取消</el-button>
          <el-button type="primary" @click="auditSubmit" :disabled="injectedModeType.mode == 'preview'">确定</el-button>
        </div>
    </template>
  </div>
</template>

<style scoped lang="scss">
.cc-apply-audit-item:not(.display-noTop){
  display: flex;
  align-items: flex-start;
  padding: 3px 0px;
  &.cc-apply-audit-title{
    font-weight: 700;
    padding: 10px 0px;
    width: 80px;
  }
}
.cc-apply-audit-title {
  width: 90px;
}
.display-noTop{
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.cc-apply-audit-content{
  max-width: 200px;
}
.cc-apply-audit-content {
  ::v-deep .el-checkbox{
    text-align: left;
    margin-right: 30px !important;
  }
  ::v-deep .el-checkbox-group{
    width: 80% !important;
  }
  ::v-deep .el-textarea{
    position: relative;
  }
  ::v-deep .el-radio{
    width: 100% !important;
    text-align: left;
    padding: 5px 0;
  }
  ::v-deep .el-radio-group{
    width: 100%;
  }
}
.cc-apply-audit-item{
  ::v-deep .el-input__inner{
    height: 32px;
  }
  ::v-deep .el-radio{
    margin-right: 10px;
  }
}
.auditInfo{
  ::v-deep{
    .el-form-item__content{
      width: 60%;
    }
    .el-form-item{
      margin-bottom: 0 !important;
    }
    .el-form-item.is-error{
      margin-bottom: 12px !important;
    }
    .el-form-item__label{
      text-align: left;
    }
    .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before{
      display: none;
    }
    .el-form-item__error{
      padding-top: 0;
    }
    .el-form-item__content{
      line-height: 40px;
    }
    .el-checkbox{
      line-height: 24px;
    }
  }
}
.cc-apply-audit-item{
  ::v-deep{
    .el-radio.is-checked.reject{
      .el-radio__label{
        color: #ff4d51;
      }
      span.el-radio__inner{
        border-color: #ff4d51;
        background-color: #ff4d51;
      }
    }
  }
}

</style>